package com.heima.media.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.heima.common.dto.ResponseResult;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.common.util.AppJwtUtil;
import com.heima.media.dto.LoginDto;
import com.heima.media.entity.WmUser;
import com.heima.media.mapper.WmUserMapper;
import com.heima.media.service.IWmUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 自媒体用户信息表 服务实现类
 * </p>
 *
 * @author wsj
 * @since 2022-03-11
 */
@Service
public class WmUserServiceImpl extends ServiceImpl<WmUserMapper, WmUser> implements IWmUserService {

    @Override
    public ResponseResult<WmUser> saveWmUser(WmUser user) {
        //根据ap_user_id查询用户是否存在
        LambdaQueryWrapper<WmUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(WmUser::getApUserId,user.getApUserId());
        WmUser one = getOne(wrapper);
        //存在，则直接返回
        if (one!=null) {
            return ResponseResult.okResult(one);
        }
        //不存在，则新增
        user.setCreatedTime(new Date());
        save(user);
        //返回
        return ResponseResult.okResult(user);
    }

    @Override
    public ResponseResult login(LoginDto dto) {
        //判断dto是否为null或用户名 密码是否为null
        //为null则返回提示：无效的参数
        if (dto==null|| StringUtils.isEmpty(dto.getName())||StringUtils.isEmpty(dto.getPassword())) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //根据用户名获取用户
        //构建查询条件
        LambdaQueryWrapper<WmUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(WmUser::getName,dto.getName());
        WmUser one = getOne(wrapper);
        //判断用户是否存在
        //不存在,返回提示：数据不存在
        if (one==null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //存在，获取盐，生成md5密码
        String passWord=dto.getPassword()+one.getSalt();
        String md5Pwd = DigestUtils.md5DigestAsHex(passWord.getBytes());
        //验证密码
        if (!md5Pwd.equals(one.getPassword())) {
            //密码不正确,返回提示：密码错误
            return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
        }
        //密码正确，制作jwt令牌
        Map<String, Object> claimMap = new HashMap<>();
        claimMap.put("userId",one.getId());
        claimMap.put("userName",one.getName());
        String token = AppJwtUtil.getToken(claimMap);
        //返回响应数据
        //脱敏处理
        one.setPassword(null);
        one.setPhone(null);
        one.setSalt(null);
        Map<String, Object> map = new HashMap<>();
        map.put("token",token);
        map.put("user",one);
        return ResponseResult.okResult(map);
    }
}
